import { gameMain } from "../GameMain";
import { IBSess } from "../../../common/interfaces";
import { MapPlayer } from "../map/MapPlayer";
import { Maps } from "../../../config/XlsxDef";
import { MsgHandler } from "kilom";
import { MsgId } from "../../../config/Msg";
import { querySql } from "../../../common/db";

export default class MsgGameLogin extends MsgHandler {

    /**
     * 进入游戏
     * @param sess 
     */
    async joinGame(sess: IBSess) {
        try {
            console.log("加入游戏！");
            let res = await querySql("select * from `player` where `pid` = ?", [sess.uid]);
            let p = res[0];
            if (!p) return sess.send(MsgId.joinGame, { code: 1, msg: "加入失败：角色不存在" });

            
            let player = new MapPlayer(sess, p);
            gameMain.addPlayer(player);
            sess.send(MsgId.joinGame, {
                code: 0, data: {
                    openTime: gameMain.openTime,
                    player: {
                        pid: player.pid,
                        sid: player.sid,
                        name: player.name,
                        career: player.career,
                        createTime: player.createTime,
                        mapId: Maps.start
                    }
                }
            });
        } catch (err) {
            sess.send(MsgId.joinGame, { code: 1, msg: "加入失败：" + (err as Error).message });
        }
    }

    /**
     * 客户端准备好进入地图了
     * @param sess 
     */
    readyEnterMap(sess: IBSess) {
        let player = gameMain.playerDic[sess.uid];
        if (player) {
            gameMain.map.addPlayer(player);
        }
        sess.send(MsgId.readyEnterMap);
    }



}